# agents/factor_agents/cipher_agent.py
from .base_factor_agent import BaseFactorAgent
from game_engine.game_state import FactorDevelopment, GameWorld
import numpy as np

class CipherAgent(BaseFactorAgent):
    """赛飞儿智能体 - 高速追击特化 [火种：诡计]"""
    
    def __init__(self, factor: FactorDevelopment, game_world: GameWorld):
        super().__init__(factor, game_world)
        self.personality_traits.update({
            "aggression": 0.75,     # 高攻击性
            "caution": 0.4,         # 低谨慎性
            "trickery": 0.9,        # 诡计多端
            "speed_priority": 0.95  # 速度优先
        })
        self.momentum_stacks = 0
        self.last_movement_time = 0
        self.pursuit_target = None
    
    def make_decision(self, current_time: int) -> str:
        """赛飞儿的决策逻辑"""
        situation = self.evaluate_situation()
        
        # 追击逻辑
        if self.pursuit_target and self.pursuit_target.is_alive:
            distance = self._calculate_distance(
                self.factor.current_location, 
                self.pursuit_target.current_location
            )
            
            if distance < 10:  # 进入攻击范围
                if self.momentum_stacks >= 2:
                    return f"momentum_attack:{self.pursuit_target.name}"
                else:
                    return f"quick_strike:{self.pursuit_target.name}"
            else:
                return f"pursue_target:{self.pursuit_target.name}"
        
        # 选择新目标
        if situation["fleeing_targets"]:
            self.pursuit_target = situation["fleeing_targets"][0]
            return f"initiate_pursuit:{self.pursuit_target.name}"
        
        # 寻找脆弱目标
        if situation["vulnerable_targets"]:
            target = min(situation["vulnerable_targets"], 
                       key=lambda x: x.attributes['health'])
            self.pursuit_target = target
            return f"target_vulnerable:{target.name}"
        
        # 积累动量
        if current_time - self.last_movement_time > 10:
            return "build_momentum"
        
        return "train_speed"
    
    def evaluate_situation(self) -> Dict:
        """评估当前局势"""
        nearby_factors = self.get_nearby_factors(25.0)
        
        fleeing_targets = []
        vulnerable_targets = []
        
        for factor in nearby_factors:
            if self._is_potential_threat(factor) or self._is_potential_prey(factor):
                # 判断是否在逃跑（有目的地且背对）
                if (factor.destination and 
                    self._is_fleeing(factor, self.factor)):
                    fleeing_targets.append(factor)
                
                # 判断是否脆弱
                if (factor.attributes['health'] < factor.attributes['health'] * 0.6 or
                    factor.attributes['defense'] < 15):
                    vulnerable_targets.append(factor)
        
        return {
            "fleeing_targets": fleeing_targets,
            "vulnerable_targets": vulnerable_targets,
            "momentum_stacks": self.momentum_stacks,
            "has_target": self.pursuit_target is not None
        }
    
    def _is_fleeing(self, target: FactorDevelopment, pursuer: FactorDevelopment) -> bool:
        """判断目标是否在逃跑"""
        if not target.destination:
            return False
        
        # 简单的逃跑判断：目的地远离追击者
        target_to_dest = self._calculate_distance(target.current_location, target.destination)
        pursuer_to_dest = self._calculate_distance(pursuer.current_location, target.destination)
        
        return pursuer_to_dest > target_to_dest + 10
    
    def _is_potential_prey(self, factor: FactorDevelopment) -> bool:
        """判断是否为潜在猎物"""
        return (factor.attributes['mobility'] < self.factor.attributes['mobility'] * 0.8 or
                factor.attributes['defense'] < 20)